import { defineStore } from "pinia";
import {
  getSalesVolume,
  getTrendData,
  getMapData,
  getRankData,
  getHotData,
  getStockData,
} from "@/api/getData";
//类型
import { sellerList, sellerItem, TrendData } from "@/types/seller";
import { Map } from "./../types/mapType";
import { rank } from "@/types/rankType";
import { hotproductList } from "@/types/hotproductType";
import { storkList } from "@/types/storkType";
import { AxiosError, AxiosResponse } from "axios";
import SocketService from "@/utils/socked_service";

const socket = SocketService.Instance;

export default defineStore("useEchartsData", {
  actions: {
    //获取商家销量图表的数据
    async getSellerData() {
      let result = await getSalesVolume();

      if (result.status === 200) {
        this.seller.sellerList = result.data.sort(
          (a: sellerItem, b: sellerItem) => b.value - a.value
        );
        //总页数
        this.seller.countPage =
          result.data.length % 5
            ? result.data.length / 5 + 1
            : result.data.length / 5;
        //当前页数
        this.seller.nowPage = 1;
      } else {
        return Promise.reject("商家销量数据获取失败");
      }
    },

    //获取销量趋势图表数据
    async getTrendData() {
      const result = await getTrendData();

      if (result.status === 200) {
        this.TrendData = result.data;
      } else {
        return Promise.reject("数据获取失败");
      }
    },

    //获取map的数据
    async getMapData() {
      let result = await getMapData();

      if (result.status === 200) {
        this.MapList = result.data;
      } else {
        return Promise.reject("获取数据失败");
      }
    },

    //获取地区销量排名
    async getRankData() {
      //往socket实例里注册函数
      socket.registerCallBack("rankData", (res: rank[]) => {
        this.rankList = res;
      });
      socket.send({
        action: "getData",
        socketType: "rankData",
        chartName: "rank",
        value: "",
      });

      // let result = await getRankData();
      // if (result.status === 200) {
      //   this.rankList = result.data;
      // } else {
      //   return Promise.reject("获取数据失败");
      // }
    },

    //获取热门产品数据
    async getHotData() {
      let result: AxiosResponse | AxiosError = await getHotData();
      if (result.status === 200) {
        this.hotproductList = result.data;
      } else {
        return Promise.reject(result);
      }
    },
    //获取库存销量数据
    async getStockData() {
      let result = await getStockData();
      if (result.status === 200) {
        this.storkList = result.data;
      } else {
        return Promise.reject(result);
      }
    },
  },
  getters: {},
  state() {
    return {
      seller: <sellerList>{},
      TrendData: <TrendData>{},
      MapList: <Map[]>{},
      rankList: <rank[]>[],
      hotproductList: <hotproductList[]>[],
      storkList: <storkList[]>[],
    };
  },
});
